﻿# coding=utf-8
from _random import Random

class Item:
    """
    砍价的目标商品
    """
    def __init__(self,bottom,middle,top):
        self.bottom = bottom
        self.middle = middle
        self.top = top
        self.count = 0


class Robot:
    """机器人类"""
    def __init__(self, max_count=3):
        self.max_count = max_count
        self.Rand = Random()
        
    def BeginBargain(self, item):
        self._item_ = item
        
    def Try(self, price):
        if self._item_ == None:                     #流程出错!!
            return (None, '乱来嘛你,你到底要买什么?')
        self._item_.count += 1
        if self._item_.count > self.max_count and self._item_.top > price:      #次数超过(并且出价低)
            return (self._item_.top, '已经说了就是这个价了怎么也不能再低了!')     
        if self._item_.top <= price :               #比最高价高直接成交
            self._item_ = None
            return (price,'好吧,成交了!')
        if self._item_.bottom > price :             #比最低价低
            result = 2 * self._item_.middle - price
            if self._item_.top > result :           #这个判断为了保证返回值不大于原来的max
                self._item_.top = result            #更新新的max
        elif self._item_.middle <= price :          #比中位价高
            self._item_.bottom = price
            self._item_.top = (self._item_.top + price)//2   #取平均值,一人退一半
        else:                                       #比中位价低,比最低价高
            diff = self._item_.top - price
            result = self.Rand.random() * diff + price
            self._item_.bottom = price
            self._item_.top = result
        if self._item_.middle < self._item_.bottom:
            self._item_.middle = self._item_.bottom
        elif  self._item_.top < self._item_.middle:
            self._item_.middle = self._item_.top
        return (self._item_.top, '这个价格行不行?')
            
            
            
            

